package com.example.data.permission.mp.config;

/**
 * Created by TD on 2021/7/20
 */

import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

/**
 * @author miemie
 * @since 2018-08-10
 */
@Configuration
@Import(cn.hutool.extra.spring.SpringUtil.class)
@MapperScan("com.example.data.permission.dao")
@EnableConfigurationProperties(DataPermissionProperties.class)
public class MybatisPlusConfig {

/*    @Autowired
    private StaticConfig staticConfig;*/

    /**
     * 新多租户插件配置,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存万一出现问题
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        // 租户插件
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // interceptor.addInnerInterceptor(getTenantLineInnerInterceptor());
        // 分页插件
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        // 数据权限
/*        DefaultDataPermissionHandler permissionHandler = new DefaultDataPermissionHandler();
        DefaultDataPermissionInterceptor dataPermissionInterceptor = new DefaultDataPermissionInterceptor(permissionHandler);
        interceptor.addInnerInterceptor(dataPermissionInterceptor);*/
        // 如果用了分页插件注意先 add TenantLineInnerInterceptor 再 add PaginationInnerInterceptor
        // 用了分页插件必须设置 MybatisConfiguration#useDeprecatedExecutor = false
        return interceptor;
    }


/*    @Bean
    public TenantLineInnerInterceptor getTenantLineInnerInterceptor() {
        TenantLineHandler tenantLineHandler = new TenantLineHandler() {
            @Override
            public Expression getTenantId() {
                UserInfo userInfo = ThreadLocalUtils.get();
                Long tenantId = userInfo.getTenantId();
                return new LongValue(tenantId);
            }

            // 这是 default 方法,默认返回 false 表示所有表都需要拼多租户条件
            @Override
            public boolean ignoreTable(String tableName) {
                return staticConfig.getIgnoreTable().contains(tableName);
            }
        };
        return new TenantLineInnerInterceptor(tenantLineHandler);
    }*/

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setUseDeprecatedExecutor(false);
    }

}

